#include "friendmodel.h"
#include "db.h"
#include <string.h>

void FriendModel::addFriend(string strMyAccount, string strFriendAccount)
{
    // 1.组装sql语句
    char sql[1024] = {0};
    sprintf(sql, "insert into friends(myaccount, friendaccount) values('%s', '%s')",
            strMyAccount.c_str(), strFriendAccount.c_str());

    MySQL mysql;
    if (mysql.connect())
    {
        mysql.update(sql);
        memset(sql, 0, sizeof(sql));
        sprintf(sql, "insert into friends(myaccount, friendaccount) values('%s', '%s')",
            strFriendAccount.c_str(), strMyAccount.c_str());
        mysql.update(sql);
    }
}

// 返回用户好友列表
vector<User> FriendModel::searchFriends(string strMyAccount)
{
    // 1.组装sql语句
    char sql[1024] = {0};

    //https://mp.weixin.qq.com/s/wjHfSb5qNKPH5k9uK5wH4w
    sprintf(sql, "select a.account,a.nickname, a.state from qousers a inner join friends b on b.friendaccount = a.account where b.myaccount=%s", strMyAccount.c_str());

    vector<User> vec;
    MySQL mysql;
    if (mysql.connect())
    {
        MYSQL_RES *res = mysql.query(sql);
        if (res != nullptr)
        {
            MYSQL_ROW row;
            while((row = mysql_fetch_row(res)) != nullptr)
            {
                User user;
                user.setAccount(row[0]);
                user.setNickName(row[1]);
                user.setState(row[2]);
                vec.push_back(user);
            }
            mysql_free_result(res);
            return vec;
        }
    }
    return vec;
}